import Taro from '@tarojs/taro'
import BaseUrl from "./baseUrl";
import {HTTP_STATUS} from "../net/status";
import common from "../common/js/common";

export default {

  /**
   *
   * @param params
   * @param method
   * @param fullUrl false: 需要拼接和院通请求地址，true：完整地址，不需要拼接和院通url
   * @return {*}
   */
  baseOptions(params, method = 'GET', fullUrl = false, isNewUrl = false) {
    let {url, data} = params;

    let token = common.getToken();

    if (!fullUrl && !isNewUrl) {
      url = BaseUrl.api_path + url;
    }

    let contentType = 'application/json';
    contentType = params.contentType || contentType;

    const option = {
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': contentType,
        'Authorization': token
      },
      success(res) {
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          Taro.showToast({title: '请求资源不存在', icon: 'none'});
          return
        } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
          Taro.showToast({title: '服务端通信失败', icon: 'none'});
          return

        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          Taro.showToast({title: '没有权限访问', icon: 'none'});
          return
        } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data;
        }
      },

      error(e) {
        Taro.showToast({title: '请求接口出现问题', icon: 'none'});
      }
    };
    return Taro.request(option);
  },

  get: async function (url, data = '') {
    let option = { url, data };
    let response = await this.baseOptions(option);
    const status = response.data.status;
    if(status === 401){
      await  common.pullToken();
      response = await this.baseOptions(option);
    }

    // return this.checkToken(this.baseOptions(option, 'GET',false, true), option, true);

    return response;
  },

  post: async function (url, data) {
    let contentType = 'application/json';
    let params = { url, data, contentType };
    let response = await this.baseOptions(params, 'POST');
    const status = response.data.status;
    if(status === 401){
      await  common.pullToken();
      response = await this.baseOptions(params, 'POST');
    }
    return response;
    // return this.checkToken(this.baseOptions(params, 'POST',false, true),params, true);
  }

}
